package singlefactory;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author gaopeng
 * @date 2019/12/7 6:32 下午
 */
public class SingleFactory {

    private static Map<Class,Object> beanMap = new HashMap<>();

    private static void createBean(Class tClass){
        try {
            Constructor constructor = tClass.getDeclaredConstructor();
            constructor.setAccessible(true);
            Object bean = constructor.newInstance();
            beanMap.put(tClass,bean);
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
            System.out.println("出错了！！！");
        }
    }

    public synchronized static Object createSingleBean(Class tClass){
        if(beanMap.get(tClass)==null){
            System.out.println(tClass.getName()+" created");
            createBean(tClass);
        }
        return beanMap.get(tClass);
    }

}
